package com.bhs.sansonglogistics.ui.enterprise;

import static com.bhs.sansonglogistics.base.MyApplication.getContext;
import static com.bhs.sansonglogistics.ui.enterprise.EnterpriseCertificationActivity.RC_LOCATION;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.ArrayMap;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.bean.AddLineBean;
import com.bhs.sansonglogistics.bean.AddOutLetsBean;
import com.bhs.sansonglogistics.bean.ArriveBean;
import com.bhs.sansonglogistics.bean.Location;
import com.bhs.sansonglogistics.bean.ShipmentsBean;
import com.bhs.sansonglogistics.dialog.CityPickerDialog;
import com.bhs.sansonglogistics.dialog.CityPickerEditDialog;
import com.bhs.sansonglogistics.dialog.MyClickListener;
import com.bhs.sansonglogistics.dialog.MyClickListener2;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.adapter.AddLineAdapter;
import com.bhs.sansonglogistics.ui.home.OrderGoodsListFragment;
import com.bhs.sansonglogistics.utils.LogUtils;
import com.bhs.sansonglogistics.utils.MyUtils;
import com.bhs.sansonglogistics.utils.SharedPreferencesUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.impl.ConfirmPopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Response;

/**
 * 添加专线
 */
public class AddLineActivity extends BaseActivity implements View.OnClickListener, NetCallBack, TextWatcher, EasyPermissions.PermissionCallbacks {


    private TextView mEtPointDeparture;
    private TextView mEtDestination;
    private EditText mEtManager;
    private EditText mEtPhone;
    private RecyclerView mRvList;
    private TextView mTvAddArrivalInformation;
    private Button mBtnSubmit;
    private AddLineAdapter mAdapter;
    private List<ArriveBean> list = new ArrayList<>();
    private RadioButton mRbNonstop;
    private RadioButton mRbTransfer;
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;
    private final AddLineBean addLineBean = new AddLineBean();
    private int position;
    private int line_id;

    @Override
    public int initLayout() {
        return R.layout.activity_add_line;
    }

    @Override
    public void initView() {

        TextView mTvTitle = findViewById(R.id.tv_title);
        mEtPointDeparture = findViewById(R.id.et_point_departure);
        mEtDestination = findViewById(R.id.et_destination);
        mEtPointDeparture.setOnClickListener(this);
        mEtDestination.setOnClickListener(this);
        mEtManager = findViewById(R.id.et_manager);
        mEtPhone = findViewById(R.id.et_phone);
        mRvList = findViewById(R.id.rv_list);
        mTvAddArrivalInformation = findViewById(R.id.tv_add_arrival_information);
        mBtnSubmit = findViewById(R.id.btn_submit);
        mBtnSubmit.setOnClickListener(this);
        mTvAddArrivalInformation.setOnClickListener(this);
        mTvTitle.setText("添加专线");
        mRbNonstop = findViewById(R.id.rb_nonstop);
        mRbTransfer = findViewById(R.id.rb_transfer);
        mEtDestination.addTextChangedListener(this);
        mEtPointDeparture.addTextChangedListener(this);
        mEtManager.addTextChangedListener(this);
        mEtPhone.addTextChangedListener(this);
        mEtManager.setFilters(MyUtils.inputFilters(this, 20));
        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                //此处是跳转的result回调方法
                if (result.getData() != null) {
                    list.get(position).setModification(true);
                    list.get(position).setOutlets_county(result.getData().getStringExtra("county"));
                    list.get(position).setOutlets_address(result.getData().getStringExtra("address"));
                    list.get(position).setOutlets_latitude(result.getData().getDoubleExtra("latitude", 0));
                    list.get(position).setOutlets_longitude(result.getData().getDoubleExtra("longitude", 0));
                    mAdapter.notifyDataSetChanged();
                    verify();
                }
            }
        });
        line_id = getIntent().getIntExtra("line_id", 0);
        if (line_id > 0) {
            networkRequest(netApi.getSpecialLineInfo(line_id), this, 9527);
        } else {
            list.add(new ArriveBean());
        }
    }

    @Override
    public void initData() {
        int logistics_id = SharedPreferencesUtils.getInt(getContext(), "logistics_id", 0);
        mAdapter = new AddLineAdapter(list, logistics_id);
        mRvList.setAdapter(mAdapter);
        mRvList.setLayoutManager(new LinearLayoutManager(mContext, RecyclerView.VERTICAL, true));
        mAdapter.setOnItemChildClickListener(new AddLineAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(View view, int position) {
                if (view.getId() == R.id.iv_location) {
                    MyUtils.hideSoftInputWindow(mActivity, view);
                    AddLineActivity.this.position = position;
                    View currentFocus = mActivity.getCurrentFocus();
                    if (currentFocus != null) {
                        currentFocus.clearFocus();
                    }
                    methodRequiresTwoPermission();
                } else {
                    new XPopup.Builder(mActivity)
                            .asConfirm("提示", "确定删除吗",
                                    "取消", "确定",
                                    new OnConfirmListener() {
                                        @SuppressLint("NotifyDataSetChanged")
                                        @Override
                                        public void onConfirm() {
                                            list.remove(position);
                                            if (list.size() == 0) {
                                                list.add(new ArriveBean());
                                            }
                                            mAdapter.notifyDataSetChanged();
                                            verify();
                                        }
                                    }, null, false)
                            .show();
                }
            }
        });

        mAdapter.setMyClickListener(new MyClickListener() {
            @Override
            public void onClick(View v) {
                verify();
            }
        });
        String address = SharedPreferencesUtils.getString(mActivity, "addressDispose");
        if (!TextUtils.isEmpty(address)) {
            addressDispose(address);
        }
    }


    String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE};

    @AfterPermissionGranted(RC_LOCATION)
    private void methodRequiresTwoPermission() {
        if (EasyPermissions.hasPermissions(this, perms)) {
            goPage();
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, "我需要您的位置信息",
                    RC_LOCATION, perms);
        }
    }


    public void goPage() {
        Intent intent = new Intent(this, LocationSelectionActivity.class);
        intent.putExtra("city", end_city);
        intentActivityResultLauncher.launch(intent);
    }

    //当申请的权限里有一个或多个被允许时
    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        if (RC_LOCATION == requestCode) {
            goPage();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn_submit) {
            addLineBean.line_contact = mEtManager.getText().toString();
            addLineBean.line_mobile = mEtPhone.getText().toString();
            addLineBean.start_province = start_province;
            addLineBean.start_city = start_city;
            addLineBean.start_county = start_county;
            addLineBean.end_province = end_province;
            addLineBean.end_city = end_city;
            addLineBean.end_county = end_county;
            addLineBean.line_type = mRbNonstop.isChecked() ? "1" : "2";
            if (dispose()) {
                upData();
            }

        } else if (view.getId() == R.id.tv_add_arrival_information) {
            if (dispose()) {
                list.get(list.size() - 1).setShowDelete(true);
                list.add(new ArriveBean());
                mAdapter.notifyDataSetChanged();
            }
        } else if (view.getId() == R.id.et_point_departure) {
            if (line_id > 0) {
                bottomSelectCity3();
            } else {
                bottomSelectCity();
            }
        } else if (view.getId() == R.id.et_destination) {
            if (line_id > 0) {
                bottomSelectCity4();
            } else {
                bottomSelectCity2();
            }
        }
    }

    private CityPickerDialog cityPickerDialog;
    private String start_province, start_city, start_county;

    private void bottomSelectCity() {
        if (cityPickerDialog == null) {
            cityPickerDialog = new CityPickerDialog(this, false);
            cityPickerDialog.setMyClickListener(new MyClickListener2() {
                @Override
                public void onClick(String id, String info) {
                    SharedPreferencesUtils.saveString(mActivity, "addressDispose", info);
                    addressDispose(info);
                }
            });
        }

        cityPickerDialog.show();
        cityPickerDialog.cityPickerReuse.setCity(start_city);
    }

    private void addressDispose(String info) {
        String[] address = info.split(",");
        start_province = address[0];
        start_city = address[1];
        start_county = address[2];
        mEtPointDeparture.setText(start_city);
    }

    private CityPickerEditDialog cityPickerEditDialog;

    private void bottomSelectCity3() {
        if (cityPickerEditDialog == null) {
            cityPickerEditDialog = new CityPickerEditDialog(this, false, start_province, start_city, start_county);
            cityPickerEditDialog.setMyClickListener(new MyClickListener2() {
                @Override
                public void onClick(String id, String info) {
                    start_county = info;
                }
            });
        }
        cityPickerEditDialog.show();
    }

    private CityPickerEditDialog cityPickerEditDialog2;

    private void bottomSelectCity4() {
        if (cityPickerEditDialog2 == null) {
            cityPickerEditDialog2 = new CityPickerEditDialog(this, true, end_province, end_city, end_county);
            cityPickerEditDialog2.setMyClickListener(new MyClickListener2() {
                @Override
                public void onClick(String id, String info) {
                    end_county = info;
                }
            });
        }
        cityPickerEditDialog2.show();
    }


    private CityPickerDialog cityPickerDialog2;
    private String end_province, end_city, end_county = "";

    private void bottomSelectCity2() {
        if (cityPickerDialog2 == null) {
            cityPickerDialog2 = new CityPickerDialog(this, true);
            cityPickerDialog2.setMyClickListener(new MyClickListener2() {
                @Override
                public void onClick(String id, String info) {
                    String[] address = info.split(",");
                    end_province = address[0];
                    end_city = address[1];
                    for (int i = 2; i < address.length; i++) {
                        end_county += address[i] + ",";
                    }
                    end_county = end_county.substring(0, end_county.lastIndexOf(','));
                    mEtDestination.setText(end_city);

                }
            });
        }

        cityPickerDialog2.show();
    }


    @SuppressLint("NotifyDataSetChanged")
    private boolean dispose() {
        ArriveBean data = list.get(list.size() - 1);
        if (!MyUtils.isPhone(mEtPhone.getText().toString())) {
            ToastUtil.show("请输入正确的经理手机号");
            return false;
        }
        if (TextUtils.isEmpty(end_province)) {
            ToastUtil.show("请填写目的地");
            return false;
        }

        if (TextUtils.isEmpty(data.getOutlets_name())) {
            ToastUtil.show("请填写到站公司");
            return false;
        }
        if (TextUtils.isEmpty(data.getOutlets_contact())) {
            ToastUtil.show("请填写专线经理");
            return false;
        }
        if (TextUtils.isEmpty(data.getOutlets_mobile())) {
            ToastUtil.show("请填到站电话");
            return false;
        }
        if (TextUtils.isEmpty(data.getOutlets_address())) {
            ToastUtil.show("请选择到站地址");
            return false;
        }

        return true;
    }

    int index = 0;

    @SuppressLint("NotifyDataSetChanged")
    private void upData() {
        if (list.size() > index) {
            if (list.get(index).isModification()) {
                ArriveBean data = list.get(index);
                uploading(data);
            } else {
                index++;
                upData();
            }
        } else {
            loadingPopupDismiss();
            gotoAdd2();
        }
    }

    private void uploading(ArriveBean data) {
        loadingPopupShow();
        Map<String, String> map = new ArrayMap<>();
        map.put("outlets_name", data.getOutlets_name());
        map.put("outlets_contact", data.getOutlets_contact());
        map.put("outlets_mobile", data.getOutlets_mobile());
        map.put("outlets_province", end_province);
        map.put("outlets_city", end_city);
        map.put("outlets_county", data.getOutlets_county());
        map.put("outlets_address", data.getOutlets_address());
        map.put("outlets_latitude", String.valueOf(data.getOutlets_latitude()));
        map.put("outlets_longitude", String.valueOf(data.getOutlets_longitude()));
        networkRequest(netApi.addOutlets(map), this);
    }


    private void gotoAdd2() {

        for (ArriveBean arriveBean : list) {
            if (TextUtils.isEmpty(addLineBean.outlets_ids)) {
                addLineBean.outlets_ids = String.valueOf(arriveBean.getOutlets_id());
            } else {
                addLineBean.outlets_ids = addLineBean.outlets_ids + "," + arriveBean.getOutlets_id();
            }
        }
        Intent intent = new Intent(AddLineActivity.this, AddLine2Activity.class);
        intent.putExtras(getIntent());
        intent.putExtra("data", addLineBean);
        startActivity(intent);

    }

    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 9527) {
            ShipmentsBean shipmentsBean = new Gson().fromJson(json, ShipmentsBean.class);
            if (shipmentsBean.isStatus()) {
                ShipmentsBean.DataDTO.InfoDTO data = shipmentsBean.getData().getInfo();
                mEtPointDeparture.setText(data.getStart_city());
                mEtDestination.setText(data.getEnd_city());
                mEtManager.setText(data.getLine_contact());
                mEtPhone.setText(data.getLine_mobile());
                mRbTransfer.setChecked(data.getLine_type() == 2);
                if (!MyUtils.isEmpty(data.getOutlets_list())) {
                    list.addAll(data.getOutlets_list());
                } else {
                    list.add(new ArriveBean());
                }
                mAdapter.notifyDataSetChanged();
                start_province = data.getStart_province();
                start_city = data.getStart_city();
                start_county = data.getStart_county();
                end_province = data.getEnd_province();
                end_county = data.getEnd_county();
                end_city = data.getEnd_city();
            } else {
                ToastUtil.show(shipmentsBean.getMsg());
            }
        } else {
            AddOutLetsBean bean = new Gson().fromJson(json, AddOutLetsBean.class);
            if (bean.isStatus()) {
                list.get(index).setOutlets_id(bean.getData().getOutlets_id());
                index++;
                upData();
            } else {
                ToastUtil.show(bean.getMsg());
            }
        }
    }

    @Override
    public void onFailure(int requestCode) {
        loadingPopupDismiss();
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        verify();
    }

    private void verify() {
        boolean verify = true;
        if (TextUtils.isEmpty(mEtDestination.getText())) {
            verify = false;
        }
        if (TextUtils.isEmpty(mEtManager.getText())) {
            verify = false;
        }
        if (TextUtils.isEmpty(mEtPhone.getText())) {
            verify = false;
        }
        if (TextUtils.isEmpty(mEtPointDeparture.getText())) {
            verify = false;
        }
        if (list.size() == 1) {
            ArriveBean data = list.get(0);
            if (TextUtils.isEmpty(data.getOutlets_address()) || TextUtils.isEmpty(data.getOutlets_mobile())
                    || TextUtils.isEmpty(data.getOutlets_name()) || TextUtils.isEmpty(data.getOutlets_contact())) {
                verify = false;
            }
        }
        mBtnSubmit.setEnabled(verify);
        mBtnSubmit.setBackgroundColor(verify ? Color.parseColor("#485EF4") : Color.parseColor("#7F485EF4"));
    }
}